﻿using HandyControl.Controls;
using HandyControl.Properties.Langs;
using HandyControl.Tools;
using HandyControl.Tools.Command;
using HandyControl.Tools.Extension;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Configuration;
using System.Windows;
using TextBox = HandyControl.Controls.TextBox;

namespace qubaohe.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {

        public string Title { get; set; }
        
        public string Files { get; set; }
        public string Edit { get; set; }

        private string _folderPath;
        public string FolderPath { get => _folderPath; set => SetProperty(ref _folderPath, value); }


        private SongDownloadModel _sdm;

        /// <summary>
        ///  构造函数
        /// </summary>
        public MainWindowViewModel()
        {
            Title = "工具集";
            this.Files = "文件";
            this.Edit = "编辑";

            // 测试数据
            //Songs.Add(new SongItem { Id = 1, SongName = "海阔天空", Author = "Beyond", DownloadProgress = 30 });
            //Songs.Add(new SongItem { Id = 2, SongName = "青花瓷", Author = "周杰伦", DownloadProgress = 75 });
            //Songs.Add(new SongItem { Id = 3, SongName = "七里香", Author = "周杰伦", DownloadProgress = 100 });
            
            FolderPath = GetSavePath();
        }
        private string _searchText;
        public string SearchText
        {
            get => _searchText;
            set { SetProperty(ref _searchText, value); }
        }


        private SongItem _selectedSongs;
        public SongItem SelectedSong
        {
            get => _selectedSongs;
            set
            {
                SetProperty(ref _selectedSongs, value);
                //if (value!= null)
                //Debug.WriteLine("选择的歌曲: " + value.SongName);

            }
        }

        private bool _isPopupOpen;
        public bool IsPopupOpen
        {
            get => _isPopupOpen;
            set { SetProperty(ref _isPopupOpen, value); }
        }

        private ObservableCollection<SongItem> _selectedItems;
        public ObservableCollection<SongItem> SelectedItems
        {
            get => _selectedItems;
            set { SetProperty(ref _selectedItems, value); }
        }

        private string _showInfo;

        /// <summary>
        /// 歌曲总数
        /// </summary>
        public string ShowInfo
        {
            get => _showInfo;
            set { SetProperty(ref _showInfo, value); }
        }

        private ObservableCollection<SongItem> _songs;
        public ObservableCollection<SongItem> Songs
        {
            get => _songs;
            set => SetProperty(ref _songs, value);
        }

        public RelayCommand DownloadCommand => new RelayCommand(Download);
        public RelayCommand DoubleClickCommand => new RelayCommand(DataGridDoubleClick);
        public RelayCommand SearchCommand => new RelayCommand(Search);
        public RelayCommand RightClickCommand => new RelayCommand(RightClick);
        public RelayCommand SaveAsCommand => new RelayCommand(SaveAs);
        public RelayCommand OpenFolderCommand => new RelayCommand(OpenFolder);

        /// <summary>
        /// 保存路径的事件处理函数
        /// </summary>
        /// <param name="obj"></param>
        private void SaveAs(object obj)
        {
            //string cd = ConfigurationManager.AppSettings["SavePath"];
             var cd= Directory.GetCurrentDirectory();


            // 创建一个 FolderBrowserDialog 实例
            var folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog
            {
                Description = "请选择保存文件的文件夹",
                
                ShowNewFolderButton = true
            };

            // 显示对话框并检查用户是否点击了“确定”
            if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // 获取用户选择的文件夹路径
                FolderPath = folderBrowserDialog.SelectedPath;
              
                using (StreamWriter sw = new StreamWriter(cd + "/setting.txt"))
                {
                    
                    sw.Write(FolderPath);
                }

            }
        }

        /// <summary>
        /// 打开文件夹的事件处理函数
        /// </summary>
        /// <param name="obj"></param>
        private void OpenFolder(object obj)
        {
            if (FolderPath != null && Directory.Exists(FolderPath))
            Process.Start(FolderPath);

        }


        /// <summary>
        /// 右键菜单的事件处理函数
        /// </summary>
        /// <param name="obj"></param>
        private void RightClick(object obj)
        {
            System.Windows.Controls.ContextMenu _menu = new ContextMenu();
            _menu.Items.Add(new MenuItem() { Header = "勾选", Command = new RelayCommand(AddSelect) });
            _menu.Items.Add(new MenuItem() { Header = "全选", Command = new RelayCommand(AllSelect) });
            _menu.Items.Add(new MenuItem() { Header = "取消选择", Command = new RelayCommand(CancelSelect) });
            _menu.Items.Add(new MenuItem() { Header = "删除" });
            _menu.Items.Add(new MenuItem() { Header = "下载所选", Command = new RelayCommand(Download) });
            _menu.IsOpen = true;
        }
        /// <summary>
        /// 添加选择菜单项的事件处理函数 ,将选中项勾选
        /// </summary>
        /// <param name="obj"></param>
        private void AddSelect(object obj)
        {
            if (SelectedItems != null && SelectedItems.Count > 0)
            {
                foreach (var item in SelectedItems)
                {
                    item.IsSelected = true;
                }
            }
        }

        /// <summary>
        /// 取消选择菜单项的事件处理函数
        /// </summary>
        /// <param name="obj"></param>
        private void CancelSelect(object obj)
        {
            if (Songs != null && Songs.Count > 0)
            {
                foreach (var item in Songs)
                {
                    item.IsSelected = false;
                }
            }
        }

        /// <summary>
        /// 全选菜单项的事件处理函数
        /// </summary>
        /// <param name="obj"></param>
        private void AllSelect(object obj)
        {
            if (Songs != null && Songs.Count > 0)
            {
                foreach (var item in Songs)
                {
                    item.IsSelected = true;
                }
            }

        }
        /// <summary>
        /// 搜索歌曲的事件处理函数
        /// </summary>
        /// <param name="text"></param>
        private void Search(object text)
        {
            // 处理搜索事件，例如显示搜索结果
            SearchText = text.ToString();
            if (string.IsNullOrEmpty(SearchText))
            {
                HandyControl.Controls.MessageBox.Show("请输入搜索内容?!!           ");

                return;
            }

            InitializeAsync(SearchText);
            this.ShowInfo = "正在搜索...";
        }

        /// <summary>
        /// 双击歌曲的事件处理函数
        /// </summary>
        /// <param name="parameter"></param>
        private void DataGridDoubleClick(object parameter)
        {
            if (parameter is SongItem selectedSong)
            {
                // 处理双击事件，例如显示选中歌曲的详细信息
                //MessageBox.Show($"双击了歌曲: {selectedSong.SongName} - {selectedSong.Author}");
                selectedSong.IsSelected = selectedSong.IsSelected == false;
            }
        }



        /// <summary>
        /// 初始化数据 搜索的主函数
        /// </summary>
        /// <param name="searchText">关键字</param>
        private async void InitializeAsync(string searchText)
        {
            if (Songs != null && Songs.Count > 0) Songs.Clear();
            _sdm = new SongDownloadModel(keyword: searchText);
            Songs = await _sdm.SearchSongsAsync();
            this.ShowInfo = SetCount(Songs.Count);
            Songs.ForEach((item) => { Debug.WriteLine(item.SongName + " - " + item.Author + " - " + item.DownloadUrl); });
        }


        /// <summary>
        /// 下载歌曲的主函数
        /// </summary>
        /// <param name="obj"></param>
        private async void Download(object obj)
        {

            if (Songs == null)
            {
                HandyControl.Controls.MessageBox.Show("请选择歌曲!");
                return;
            }
            else
            {
                int count = 0;
                foreach (var item in Songs)
                {
                    if (item.IsSelected == true) count++;
                }
                if (count == 0)
                {
                    HandyControl.Controls.MessageBox.Show("请选择歌曲!");
                    return;
                }
            }

            if (string.IsNullOrEmpty(FolderPath))
            {
                HandyControl.Controls.MessageBox.Show("请选择保存文件夹!  左上角文件-保存于...");
                return;
            }

            this.ShowInfo = "正在下载...";
            foreach (var item in Songs)
            {
                if (item.IsSelected == false) continue;
                var downloadUrl = await _sdm.GetDownloadUrlAsync(item.Url);
                item.DownloadUrl = downloadUrl;
                await _sdm.DownloadFileAsync(item, FolderPath + "\\" + item.SongName + "--" + item.Author + ".mp3");
                //Debug.WriteLine("下载歌曲: " + item.SongName + "url" + item.Url);

                await _sdm.   DownloadLyricAsync(item, FolderPath+ "\\" + item.SongName+"--"+item.Author+ ".lrc"); 
            }

            IsPopupOpen = true;
            //Growl.Success("已全部下载完成");
            this.ShowInfo = "已全部下载完成.";
            await Task.Delay(10000); // 延迟 3 秒 
            IsPopupOpen = false;

            //Growl.Clear();
           
           
        }

        


        /// <summary>
        /// 设置歌曲总数
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        private string SetCount(int count)
        {
            return "搜索到" + count.ToString() + "首歌曲.";
        }


        /// <summary>
        /// 获取保存路径
        /// </summary>
        /// <returns></returns>
        private string GetSavePath()
        {
            string savePath = "";
            if (File.Exists("setting.txt"))
            {
                using (StreamReader sr = new StreamReader("setting.txt"))
                {
                    savePath = sr.ReadLine();
                }
            }
            return savePath;    
        }
    }
}
